package com.tnxst.phexamination.fragment.follow;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tnxst.phexamination.R;
import com.tnxst.phexamination.adapter.follow.AddFollowDrugAdapter;
import com.tnxst.phexamination.databinding.DoorRecordHypertensionFollowupTwoBinding;

import com.tnxst.phexamination.dto.HypertensionFollowDTO;
import com.tnxst.phexamination.dto.InhabitantDTO;
import com.tnxst.phexamination.utils.GsonUtils;
import com.tnxst.phexamination.utils.PictureFileUtil;
import com.tnxst.phexamination.utils.StringUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;
import com.tnxst.phexamination.vo.DrugVo;

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import worker8.com.github.radiogroupplus.RadioGroupPlus;

public class NewbornFamilyFollowFragment extends Fragment implements CompoundButton.OnCheckedChangeListener{


    private Context context;

    private GlobalViewModel viewModel;

    private HypertensionFollowDTO hypertensionFollowDTO;

    private List<DrugVo> drug;

    private List<Map<String, Object>> other;

    private List<String> laboratoryString;

    private Map<String, Object> labora;

    private InhabitantDTO inhabitantDTO;

    private AddFollowDrugAdapter addFollowDrugAdapter;

    //新增定位功能及拍照功能的控件
    private EditText address;

    private ImageView picture1;

    private ImageView picture2;

    private ImageView picture3;

    private Switch aSwitch;

    private Button start;

    private TextView del1;

    private TextView del2;

    private TextView del3;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
//        binding = DataBindingUtil.inflate(inflater, R.layout.record_visit_newbaby, container, false);
//        context = container.getContext();
//        return binding.getRoot();
        return  null;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(requireActivity()).get(GlobalViewModel.class);
        initData();
        initView();
//        initAddress();
    }

    private void initAddress() {
//        address = binding.include.findViewById(R.id.editTextTextPersonName33);
//        picture1 = binding.include.findViewById(R.id.image1);
//        picture2 = binding.include.findViewById(R.id.image2);
//        picture3 = binding.include.findViewById(R.id.image3);
//        aSwitch = binding.include.findViewById(R.id.isFinish);
//        start = binding.include.findViewById(R.id.button22);
//        del1 = binding.include.findViewById(R.id.text1);
//        del2 = binding.include.findViewById(R.id.text2);
//        del3 = binding.include.findViewById(R.id.text3);
        viewModel.getAddressUtils().getAddress(address, getActivity());


    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            // 图片选择结果回调
            hypertensionFollowDTO.setPicturePath1("");
            hypertensionFollowDTO.setPicturePath2("");
            hypertensionFollowDTO.setPicturePath3("");
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture1);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture2);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture3);

            List<LocalMedia> selectListPic = PictureSelector.obtainMultipleResult(data);
            hypertensionFollowDTO.setPicturePath1(selectListPic.size() > 0 ? selectListPic.get(0).getRealPath() : "");
            hypertensionFollowDTO.setPicturePath2(selectListPic.size() > 1 ? selectListPic.get(1).getRealPath() : "");
            hypertensionFollowDTO.setPicturePath3(selectListPic.size() > 2 ? selectListPic.get(2).getRealPath() : "");
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath1(), picture1);
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath2(), picture2);
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath3(), picture3);
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        //病人信息
//        binding.editText2.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                String idCard = s.toString();
//                if (idCard.length() >= 2 ){
//                    List<InhabitantDTO> dtoList = viewModel.getInhabitantRepository().findByFieldList("NAME", idCard);
//                    if (!CollectionUtils.isEmpty(dtoList)){
//                        InhabitantDTO i = dtoList.get(0);
//                        if (i != null){
//                            inhabitantDTO = i;
////                            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
////                                TuberculosisInterface.verifyIsTbPatient(inhabitantDTO.getID(), new WebServiceUtils.Response<Map>() {
////                                    @Override
////                                    public void onSuccess(Map result) {
////                                        String is = result.get("Msg").toString();
////                                        if ("1.0".equals(is)){
////                                            return;
////                                        }
////                                    }
////                                    @Override
////                                    public void onError(String error) {
////                                        Utils.Toast(context,"验证患者是否失败！\n失败原因：" + error);
////                                    }
////                                });
////                            }
//                            setInhabitantView();
//                        }else {
//                            clearInhabitantView();
//                        }
//                    }else {
//                        clearInhabitantView();
//                        inhabitantDTO = null;
//                    }
//                }
//            }
//        });


//        binding.textView722.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
//                    @Override
//                    public void onTimeSelect(Date date, View v) {
//
//                    }
//                })
//                        .setType(new boolean[]{true, true, true, false, false, false})
//                        .setTitleText("随访时间")
//                        .setTitleColor(Color.WHITE)//标题文字颜色
//                        .setSubmitColor(Color.parseColor("#43c489"))
//                        .setCancelColor(Color.parseColor("#43c489"))
//                        .setTitleBgColor(Color.parseColor("#43c489"))
//                        .setDividerColor(Color.parseColor("#43c489"))
//                        .setTextColorCenter(Color.parseColor("#43c489"))
//                        .setTitleSize(14)
//                        .setContentSize(14)
//                        .setSubCalSize(14)
//                        .build();
//
//                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
//                pvTime.show();
//            }
//        });


        //设置常用药品的流式布局
//        binding.textView179.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
//                View view = View.inflate(getActivity(), R.layout.dialog_sex, null);
//                alertDialog
//                        .setView(view)
//                        .create();
//                final AlertDialog show = alertDialog.show();
//                TextView tv_boy = view.findViewById(R.id.tv_boy);
//                TextView tv_girl = view.findViewById(R.id.tv_girl);
//                TextView btn_cancel = view.findViewById(R.id.btn_cancel);
//                TextView btn_commit = view.findViewById(R.id.btn_commit);
//
//
//                btn_cancel.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        show.dismiss();
//                    }
//                });
//
//                btn_commit.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//
//                    }
//                });
//            }
//        });








    }

    /**
     * 初始化数据
     */
    private void initData() {
        laboratoryString = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.exam_laboratory_adapter)));
        Bundle arguments = getArguments();

        if (arguments == null){
            hypertensionFollowDTO = new HypertensionFollowDTO();
            labora = new LinkedHashMap<>();
            drug = new ArrayList<>();
            other = new ArrayList<>();
        }
        else {
            hypertensionFollowDTO = (HypertensionFollowDTO) arguments.get("hypertensionFollowDTO");
            labora = GsonUtils.fromJson(hypertensionFollowDTO.getLabora(),Map.class);
            drug = GsonUtils.jsonToList(hypertensionFollowDTO.getDrug(),DrugVo.class);
            other = GsonUtils.fromJson(hypertensionFollowDTO.getOther(),List.class);
            inhabitantDTO = viewModel.getInhabitantRepository().findByField("ID",hypertensionFollowDTO.getPersonID());
            if (inhabitantDTO == null){
                Utils.Toast(context,"请先更新病人数据！");
                hideAddFragment();
                return;
            }

        }
    }





    /**
     * 设置other值
     * @param key
     * @param value
     */
    private void setMap(String key, String value) {
        Map<String,Map> keys = new HashMap<>();
        for (Map<String, Object> map : other) {
            String k = map.get("AttrName").toString();
            keys.put(k,map);
        }
        if (keys.keySet().contains(key)){
            Map map = keys.get(key);
            map.put("OtherText",value);
        }else {
            Map map = new HashMap();
            map.put("AttrName",key);
            map.put("OtherText",value);
            other.add(map);
        }
    }

    /**
     * 隐藏Fragment
     */
    private void hideAddFragment() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(this);
        ft.commitAllowingStateLoss();
    }

    private void setInhabitantView(){
//        binding.textView177.setText(inhabitantDTO.getNAME());
//        if ("1".equals(inhabitantDTO.getSEX()))
//            binding.textView179.setText("男");
//        else if ("2".equals(inhabitantDTO.getSEX()))
//            binding.textView179.setText("女");
//        binding.textView183.setText(inhabitantDTO.getTEL());
//        binding.textView184.setText(inhabitantDTO.getIDCARD());
    }

    private void clearInhabitantView(){

    }



    /**
     * 计算症状总值
     * @return
     */


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }
}
